package com.sinoglobal.ningxia.activity;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.base.BaseActivity;
import com.sinoglobal.ningxia.adapter.MyActivityAdapter;
import com.sinoglobal.ningxia.beans.AdverVo;
import com.sinoglobal.ningxia.beans.MyActivityInfoVo;
import com.sinoglobal.ningxia.beans.MyActivityVo;
import com.sinoglobal.ningxia.beans.RootVo;
import com.sinoglobal.ningxia.dialog.DialogBuilder;
import com.sinoglobal.ningxia.dialog.MDialogMethod;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.utils.FlyUtil;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;

import net.tsz.afinal.FinalBitmap;

import java.util.ArrayList;

/**
 * 
 * @author wxy
 * @createdate 2014-6-25 上午9:30:59
 * @Description: 左侧栏点击“我的活动”进入的界面，该界面的每条活动是从首页的活动中点击“领取活动码”而显示在“我的活动”中的。
 */
public class MyActivity extends BaseActivity {

	private ImageView myActivityBack; // 标题栏的返回按钮
	private ImageView myActivityClear;// 标题栏的清空按钮
	private ListView myActivityListview;// 显示“我的活动”列表
	private MyActivityAdapter myActivityAdapter;// 显示“我的活动”列表的adapter
	private ArrayList<MyActivityInfoVo> myActivityInfoVos = new ArrayList<MyActivityInfoVo>();// 我的活动的数据集合
	private Intent intent = null;// 点击某一活动跳转到活动详情的intent，传递点击的id值
	private ImageView adverImg, closeAdver;// 广告位,广告位的关闭按钮
	private AdverVo adver;// 广告信息的bean

	private TextView myActivityNoDataShow;// 没有活动的时候提示给用户
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		isTemplate = false;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_activity);
		openChenJInShi();//开启沉浸式
		init();
		addListener();
		loadInfo();
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					downLoadAdver();
					break;

				default:
					break;
				}
			}
		};
	}

	/**
	 * 
	 * @author wxy
	 * @createdate 2014-6-25 上午9:34:09
	 * @Description: 初始化控件
	 * 
	 */
	private void init() {
		myActivityNoDataShow = (TextView) findViewById(R.id.my_activity_no_data_show);
		myActivityBack = (ImageView) findViewById(R.id.my_activity_back);
		myActivityClear = (ImageView) findViewById(R.id.my_activity_clear);
		myActivityListview = (ListView) findViewById(R.id.my_activity_listview);
		closeAdver = (ImageView) findViewById(R.id.close_advertising);
		adverImg = (ImageView) findViewById(R.id.advertising);
		// 设置广告位的宽高比例为1:6
		DisplayMetrics dm=new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		RelativeLayout.LayoutParams params = (LayoutParams) adverImg
				.getLayoutParams();
		params.height = dm.widthPixels * 43 / 320;
		adverImg.setLayoutParams(params);
	}

	/**
	 * 
	 * @author wxy
	 * @createdate 2014-6-25 上午9:34:23
	 * @Description: 添加点击事件
	 * 
	 */
	private void addListener() {
		myActivityBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MyActivity.this.finish();

			}
		});
		// 点击清空按钮弹出“再想想”，“确定”的提示框
		myActivityClear.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (myActivityInfoVos.size() == 0) {
					showShortToastMessage(getString(R.string.have_no_activitys));
				} else {
					final DialogBuilder dialogBuilder = new DialogBuilder(
							MyActivity.this);
					// 选择dialogBuilder中有两个button的构造方法
					dialogBuilder.Dialogbtn2(
							getString(R.string.sure_clearAll_activitys),
							R.layout.dialog_two_button, new MDialogMethod() {

								@Override
								public void dialogOk() {

									// 请求服务器告诉后台清空列表
									new ItktAsyncTaskWithDialog<Void, Void, RootVo>(
											getString(R.string.clearing_activitys),
											true, true) {

										@Override
										public RootVo before(Void... params)
												throws Exception {
											// 第二个参数id传“”的时候代表清空所有
											return RemoteImpl
													.getInstance()
													.deleteMyActivity(
															FlyApplication.userId,
															MContants.EMPTY_STRING);
										}

										@Override
										public void after(RootVo result) {
											if (result != null) {
												if (Code.CODE_SUCCESS != result
														.getCode()) {
													showShortToastMessage(result
															.getMessage());
													// 清空之后要消失改dialog
													dialogBuilder.mdialog
															.dismiss();
												} else {
													showShortToastMessage(result
															.getMessage());
													// 清空所有列表
													myActivityInfoVos.clear();
													myActivityAdapter
															.notifyDataSetChanged();
													// 清空之后要消失改dialog
													dialogBuilder.mdialog
															.dismiss();

												}
											}

										}

										@Override
										public void exception() {
											// Auto-generated method stub

										}
									}.execute();

								}

								@Override
								public void dialogCancel() {
									dialogBuilder.mdialog.dismiss();
								}
							});
				}
			}
		});
		// 广告位的点击事件
		adverImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!isNetworkConnected(FlyApplication.context)) {
					showShortToastMessage(getString(R.string.no_network_checknet));
					return;
				}
				try {
					// 打开默认浏览器显示网页信息
					Uri uri = Uri.parse(adver.getAd_url());
					Intent intent = new Intent(Intent.ACTION_VIEW, uri);
					startActivity(intent);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		// 关闭广告位点击事件
		closeAdver.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				adverImg.setVisibility(View.GONE);
				closeAdver.setVisibility(View.GONE);
			}
		});
	}

	/**
	 * 
	 * @author wxy
	 * @createdate 2014-6-25 上午10:02:56
	 * @Description: (从服务器加载“我的活动”列表的信息)
	 * 
	 */
	private void loadInfo() {
		adverImg.setVisibility(View.GONE);
		new ItktAsyncTaskWithDialog<Void, Void, MyActivityVo>(
				getString(R.string.get_list_activity), true, true) {

			@Override
			public MyActivityVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getMyActivityVo(
						FlyApplication.userId);
			}

			@Override
			public void after(MyActivityVo result) {

				if (result != null) {
					if (Code.CODE_SUCCESS != result.getCode()) {
						showShortToastMessage(result.getMessage());
					} else {
						// 从服务器获得的数据通过myActivityAdapter显示到列表上
						if (0 != result.getList().size()) {
							myActivityInfoVos = result.getList();
							myActivityAdapter = new MyActivityAdapter(
									myActivityInfoVos, MyActivity.this);
							myActivityListview.setAdapter(myActivityAdapter);
							// 删除用户长按所选择的活动 或者 用户点击某一活动进入到活动详情页面
							myActivityNoDataShow.setVisibility(View.GONE);
							choice();
						} else {
							// 提示用户当前无活动
							myActivityNoDataShow
									.setVisibility(View.VISIBLE);
						}
						handler.sendEmptyMessage(1);

					}
				}

			}

			@Override
			public void exception() {

			}
		}.execute();

	}

	/**
	 * 
	 * @author wxy
	 * @createdate 2014-6-25 下午5:52:09
	 * @Description: (删除用户所选择的那条活动)
	 * @param activityInfoVos
	 * 
	 */
	private void choice() {
		// 长按某一条 弹出提示框提示是否删除该条item
		myActivityListview
				.setOnItemLongClickListener(new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> arg0,
							final View arg1, final int arg2, long arg3) {
						final DialogBuilder dialogBuilder = new DialogBuilder(
								MyActivity.this);
						// 选择dialogBuilder中有两个button的构造方法
						dialogBuilder.Dialogbtn2(
								getString(R.string.sure_delete_activity),
								R.layout.dialog_two_button,
								new MDialogMethod() {

									@Override
									public void dialogOk() {
										// 请求服务器，告诉后台删除的活动
										new ItktAsyncTaskWithDialog<Void, Void, RootVo>() {

											@Override
											public RootVo before(Void... params)
													throws Exception {
												// 第二个参数id传“”的时候代表清空所有
												return RemoteImpl
														.getInstance()
														.deleteMyActivity(
																FlyApplication.userId,
																myActivityInfoVos
																		.get(arg2)
																		.getId());
											}

											@Override
											public void after(RootVo result) {
												if (result != null) {
													if (Code.CODE_SUCCESS != result
															.getCode()) {
														showShortToastMessage(result
																.getMessage());
														// 清空之后要消失改dialog
														dialogBuilder.mdialog
																.dismiss();
													} else {
														showShortToastMessage(getString(R.string.delete_success));
														// 清空之后要消失改dialog
														dialogBuilder.mdialog
																.dismiss();
														// 点击确定按钮，删除该条活动
														myActivityInfoVos
																.remove(arg2);
														myActivityAdapter = new MyActivityAdapter(
																myActivityInfoVos,
																MyActivity.this);
														myActivityListview
																.setAdapter(myActivityAdapter);
														myActivityAdapter
																.notifyDataSetChanged();
													}
												}

											}

											@Override
											public void exception() {
												// Auto-generated method stub

											}
										}.execute();

									}

									@Override
									public void dialogCancel() {
										dialogBuilder.mdialog.dismiss();

									}
								});
						return false;
					}
				});

		// 点击某一项查看活动的详情
		myActivityListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
				intent = new Intent(MyActivity.this, EnentItemActivity.class);
				intent.putExtra("id", myActivityInfoVos.get(position).getId());
				FlyUtil.intentForward(MyActivity.this, intent);
			}
		});
	}

	// 下载广告信息
	private void downLoadAdver() {
		adver = new AdverVo();
		new ItktAsyncTaskWithDialog<Void, Void, AdverVo>(
				getString(R.string.downloading), false, true) {

			@Override
			public AdverVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().downLoadAdver();
			}

			@Override
			public void after(AdverVo result) {
				if (null == result) { // 数据为空
					return;
				}
				if (Code.CODE_SUCCESS != result.getCode()) {// 判断返回的是否需要更新的code值
					return;
				}
				// adver = result;
				adver.setAd_img(result.getAd_img());
				adver.setAd_url(result.getAd_url());
				try {
					String url = ConnectionUtil.localUrl + adver.getAd_img();
					ItktLog.i("--------ad   url-------->>>>>>>>>>>>" + url);
					if (MContants.EMPTY_STRING.equals(adver.getAd_img())) {// 获取图片地址为空时，显示默认图片
						adverImg.setVisibility(View.GONE);
					} else {
						adverImg.setVisibility(View.VISIBLE);
						FinalBitmap fb = FinalBitmap
								.create(FlyApplication.context);
						fb.display(adverImg, url);// 将图片显示在广告位上
						closeAdver.setVisibility(View.VISIBLE);
					}
					SharedPreferenceUtil.saveString(FlyApplication.context,
							"ad_name", result.getAd_name());
					SharedPreferenceUtil.saveString(FlyApplication.context,
							"ad_img", result.getAd_img());
					SharedPreferenceUtil.saveString(FlyApplication.context,
							"ad_url", result.getAd_url());
				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			@Override
			public void exception() {
			}
		}.execute();
	}

	// 判断是否连接网络
	public boolean isNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}
}
